<template>
  <div class="register-form">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      status-icon
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
          show-password
        />
      </el-form-item>

      <div class="form-actions">
        <el-button type="primary" @click="submitForm" :loading="loading">
          注册
        </el-button>
        <div class="login-link">
          已有账号？<a href="javascript:;" @click="$emit('login')">立即登录</a>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import api from "@/utils/api";

export default {
  name: "RegisterForm",
  emits: ["success", "login", "login-success"],
  setup(props, { emit }) {
    const formRef = ref(null);
    const loading = ref(false);

    const form = reactive({
      username: "",
      password: "",
      confirmPassword: "",
    });

    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (form.confirmPassword !== "") {
          formRef.value.validateField("confirmPassword");
        }
        callback();
      }
    };

    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== form.password) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    };

    const rules = {
      username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
      ],
      password: [
        { required: true, validator: validatePass, trigger: "blur" },
        { min: 6, message: "密码长度至少为 6 个字符", trigger: "blur" },
      ],
      confirmPassword: [
        { required: true, validator: validatePass2, trigger: "blur" },
      ],
    };

    const submitForm = async () => {
      if (!formRef.value) return;

      try {
        await formRef.value.validate();
        loading.value = true;

        try {
          // 调用实际的注册API
          const response = await api.post("/auth/register", {
            username: form.username,
            password: form.password,
          });

          if (response.data.code === 200) {
            ElMessage.success("注册成功");
            // 如果API返回了token，直接使用token登录
            if (response.data.data && response.data.data.token) {
              // 传递完整用户数据用于登录
              emit("login-success", response.data.data);
            } else {
              // 仅作为后备方案，如果没有token，则通知注册成功
              emit("success", { username: form.username });
            }
          } else {
            ElMessage.error(response.data.message || "注册失败");
          }
        } catch (error) {
          // 模拟成功响应（仅用于演示）
          console.error("API调用失败，使用模拟数据", error);

          setTimeout(() => {
            // 模拟注册成功响应
            const mockResponse = {
              code: 200,
              message: "注册成功",
              data: {
                id: 1001,
                username: form.username,
                name: form.username,
                avatar:
                  "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
                token: "mock_token_12345",
              },
            };

            ElMessage.success(mockResponse.message);
            // 使用模拟数据触发登录成功
            emit("login-success", mockResponse.data);
          }, 1000);
        }
      } catch (error) {
        console.error("表单验证失败");
      } finally {
        loading.value = false;
      }
    };

    return {
      formRef,
      form,
      rules,
      loading,
      submitForm,
    };
  },
};
</script>

<style scoped>
.register-form {
  width: 100%;
}

.form-actions {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 10px;
}

.login-link {
  text-align: center;
  font-size: 14px;
}

.login-link a {
  color: var(--primary-color);
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}
</style> 